﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YArchitech.HYSpace
{
	[Transaction(TransactionMode.Manual)]
	public class ChangeThick : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			if (cmdData == null)
			{
				throw new System.ArgumentNullException();
			}
			UIDocument activeUIDocument = cmdData.Application.ActiveUIDocument;
			if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
			{
				(ViewType)1,
				(ViewType)2
			}))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Result result;
			try
			{
				transaction = new Transaction(activeUIDocument.Document, "www.hongye.com");
				double dNewThick = 0.0;
				for (;;)
				{
					WallFilter wallFilter = new WallFilter();
					Reference reference = cmdData.Application.ActiveUIDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, wallFilter, "请选择要改变保温层厚度的墙体：");
					Wall wall = cmdData.Application.ActiveUIDocument.Document.GetElement(reference) as Wall;
					WallType wallType = wall.WallType;
					if (wallType.Kind != null)
					{
						break;
					}
					foreach (CompoundStructureLayer compoundStructureLayer in wallType.GetCompoundStructure().GetLayers())
					{
                        if ((int)compoundStructureLayer.Function == 3)
						{
							dNewThick = compoundStructureLayer.Width * 304.8;
						}
					}
					if (new DlgChangeWallThick(cmdData, ref message, elements, wall)
					{
						m_dNewThick = dNewThick
					}.ShowDialog() == DialogResult.Cancel)
					{
						goto Block_8;
					}
				}
				MessageBox.Show("不支持叠层墙。", "盈建科提示");
				return Autodesk.Revit.UI.Result.Cancelled;
				Block_8:
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
                    if ((int)status == 1)
					{
						transaction.Commit();
					}
                    else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
